/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package it.unitn.science.matr155863_148346_145963.bccastestore.servlet;

import it.unitn.science.matr155863_148346_145963.bccastestore.DBManager;
import it.unitn.science.matr155863_148346_145963.bccastestore.items.Asta;
import it.unitn.science.matr155863_148346_145963.bccastestore.items.User;
import it.unitn.science.matr155863_148346_145963.bccastestore.utils.MailSender;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.UnavailableException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;

/**
 *
 * @author Luciano
 */
public class AnnullaAstaSRV extends HttpServlet {
    
    private DBManager db=null;
    private static Logger log = Logger.getLogger(RegisterUserSRV.class);
    
    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        try {
          db=(DBManager)super.getServletContext().getAttribute("db_manager");
        }catch(Exception e) {
            log.fatal(e);
            throw new UnavailableException(e.toString());
        }
    }

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        String address="/contents/public/errorPage.jsp";
        try {
            if(request.getParameter("id")!=null){
                Integer idAsta=Integer.parseInt(request.getParameter("id"));
                if(db.annullaAsta(idAsta)){
                    request.setAttribute("message", "L' asta e' stata annullata con successo");
                    address="/contents/public/home.jsp";
                    List<String> emails=db.getEmailsPartecipantiAdAsta(idAsta);
                    Asta asta=db.getAsta(idAsta);
                    String text="L'asta :"+asta.getId()+"\n"
                            + "inrente al prodotto: "+asta.getProduct().getName()+"\n"
                            + "messo in vendita da: "+asta.getSeller().getUsername()+"\n"
                            + "e' stata annullata.";
                    for(String email:emails){                        //Devo generare un numero casuale perche' altrimenti dai dati un malitenzionato potrebbe capire il codice e aggirare la protezione
                        MailSender.sendTextMailWithAutentication("daghen.de.pu@gmail.com", "daghen.de.pu", "daghendepu@gmail.com", email, "Asta annulled", text);
                    }
                    User seller=db.getUser(asta.getSellerId());
                    text=text+"\nIn quanto venditore dell'asta sei tenuto a versarci un gettone da 1.23€";
                    MailSender.sendTextMailWithAutentication("daghen.de.pu@gmail.com", "daghen.de.pu", "daghendepu@gmail.com", seller.getEmail(), "Asta annulled", text);
                    //MANDARE MAIL AI PARTECIPANTI!!!
                    //PRIMA BISOGNA IMPLEMENT LA PARTE DI FAR OFFERTE
                }else{
                    request.setAttribute("message", "errore nel annullare asta");
                }
            }else{
                //No asta defined
                request.setAttribute("error_message", "No asta defined");
            }
            
        }catch(Exception e){
            log.error(e);
        }finally{
            RequestDispatcher dispatcher=request.getRequestDispatcher(address);
            dispatcher.include(request, response);
        }
               
    
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
